<?php
namespace app\common;
use app\admin\model\Page;

class Fileoperator
{

    protected $filepath = '';

    protected $pagepath = '';

    public function uploadFile()
    {
        $files = request()->file();
        try{
            validate(['image' => 'filesize:10240|fileExt:jpg|image:200,200,jpg'])
                ->check($files);
            $savename = [];
            foreach($files as $file){
                $savename[] = \think\facade\Filesystem::putFile('topic',$file);
            }
        } catch(think\exception\ValidateException $e){
            echo $e->getMessage();
        }
    }

    //only one floor
    public function scanDir($DirName)
    {
        $DirName = $this->filepath.$DirName;
        if(!is_dir($DirName)){
            return false;
        }

        $dirs = opendir($DirName);

        if(!$dirs){
            return false;
        }

        $files = [];
        while(($file = readdir($dirs)) !== false){
            if($file == '.' || $file == '..'){
                continue;
            }
            if(is_file($file)){
              array_push($files, $DirName.$file);
            }
        }

        closedir($dirs);

        return $files;

    }

    public function scanPages($DirName)
    {
        $DirName = $this->filepath.$DirName;
        if(!is_dir($DirName)){
            return false;
        }

        $dirs = opendir($DirName);
        if(!$dirs){
            return false;
        }

        $files = [];
        while(($file = readdir($dirs)) !== false){
            if($file == '.' || $file == '..'){
                continue;
            }
            if(is_file($file)){
                array_push($files, $DirName.$file);
            }
        }
        closedir($dirs);
        return $files;
    }

    public function makeFile($fileName, $content)
    {
        $path = $this->pagepath.$fileName;

        $fil = fopen($path, $content);

        if(!$fil){
            return false;
        }

        fwrite($fil, $content);

        return true;
    }
}
